package com.qqbot.impl.utils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * Linux 系统命令执行工具类
 *
 * @author changwenpeng
 */
@Slf4j
public class LinuxCmdUtils {

    /**
     * 执行linux命令
     *
     * @param command linux命令
     * @return
     */
    public static boolean executeCmd(String command) {
        log.info("Execute command:{}", command);
        boolean result = false;
        Runtime run = Runtime.getRuntime();
        try {
            Process process = run.exec(command);
            //执行结果 0 表示正常退出
            int exeResult = process.waitFor();
            if (exeResult == 0) {
                result = true;
            }
        } catch (Exception e) {
            log.error("Execute command:{}, error:{}", command, e);
        }
        return result;
    }

    /**
     * 获取Linux进程的PID
     *
     * @param processName 进程名称
     * @return
     */
    public static String getPID(String processName) {
        BufferedReader reader = null;
        try {
            //显示所有进程
            Process process = Runtime.getRuntime().exec("ps -ef");
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (line.contains(processName)) {
                    String[] strs = line.split("\\s+");
                    return strs[1];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {

                }
            }
        }
        return null;
    }

    /**
     * 关闭Linux进程
     *
     * @param pid 进程的PID
     */
    public static void killProc(String pid) {
        log.info("关闭应用程序:{}", pid);
        Process process = null;
        BufferedReader reader = null;
        try {
            //杀掉进程
            process = Runtime.getRuntime().exec("kill -9 " + pid);
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                log.info(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 获取linux命令执行的结果
     *
     * @param command linux命令
     * @return
     */
    public static String getCmdResult(String command) {
        String result = "";
        try {
            Process process = Runtime.getRuntime().exec(command);
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            while ((line = input.readLine()) != null) {
                result = line;
            }
        } catch (IOException e) {
            log.error("IOException", e);
        }
        return result;
    }

    /**
     * 获取shell命令执行的结果
     *
     * @param shellCmd shell命令
     * @return
     */
    public static String getShellResult(String shellCmd) {
        String[] cmd = new String[3];
        cmd[0] = "/bin/sh";
        cmd[1] = "-c";
        cmd[2] = shellCmd;

        //得到Java进程的相关Runtime运行对象
        Runtime runtime = Runtime.getRuntime();
        StringBuffer stringBuffer = null;
        try {
            Process process = runtime.exec(cmd);
            BufferedReader bufferReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            stringBuffer = new StringBuffer();
            String temp = null;
            while ((temp = bufferReader.readLine()) != null) {
                stringBuffer.append(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }

    public static void main(String[] args) {
        //downfile = "D:\\DownFile\\DownFile.exe";
        String cmd = System.getProperty("user.dir") + "\\bat\\start";
        String batFile = System.getProperty("user.dir") + "\\bat\\start.bat";
        String batCmd = "cd /d C:\\Users\\changwenpeng\\Desktop\\go-cqhttp && go-cqhttp.exe faststart";
        String procName = "go-cqhttp.exe";
        boolean exist = WindowsCmdUtils.findProcess(procName);
        try {
            if (exist) {
                // 存在，那么就先杀死该进程
                WindowsCmdUtils.killProc(procName);
                // 在启动
                WindowsCmdUtils.executeCmd(cmd);
            } else {
                WindowsCmdUtils.executeCmds(cmd, batFile, batCmd);
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("重启/杀死提取程序失败。。。");
        }
    }
}